from selenium import webdriver
import time
import os
from tkinter import *
from tkinter.messagebox import *

browser = webdriver.Chrome()
selectMenu =["有害其他", "有害暴恐", "涉黄低俗", "人身攻击", "垃圾营销", "恶意营销"]
complainType = ["有害信息","有害信息","涉黄信息", "人身攻击", "垃圾营销", "恶意营销", "诈骗信息"]
compSubType = ['其他有害信息',"暴恐血腥","低俗信息", "人身攻击我", "其他广告", "引战", "票务诈骗"]
attackReason = u"该微博长期恶意人身攻击艺人，发布虚假信息，用词恶劣，对个人名誉产生非常负面的影响，微博是一个有着广泛影响力的公众平台，需尽心维护良好的网络秩序，对于恶意攻击行为请严肃处理，谢谢"
weiboMainPage = 'https://passport.weibo.cn/signin/login?entry=mweibo&res=wel&wm=3349&r=http%3A%2F%2Fm.weibo.cn%2F'
dlCompainMainPages = ["",'https://m.weibo.cn/p/2304133730167720_-_WEIBO_SECOND_PROFILE_WEIBO', 'https://m.weibo.cn/profile/6631844813']
dlCompainMainPage = 'https://m.weibo.cn/p/2304133730167720_-_WEIBO_SECOND_PROFILE_WEIBO'

root = Tk()

running = 1

def IsLogined():
    try:
        browser.find_element_by_class_name('nav-main') # mobile
        return True
    except:
        False
    try:
        browser.find_element_by_class_name('WB_miniblog') # pc
        return True
    except:
        False
    return False

def Weibo_login():
    browser.get(weiboMainPage)
    while IsLogined() == False:
        time.sleep(2)
    browser.get(dlCompainMainPage)
    ShowMenu()

def GetArticles(articleId):
    pagecnt = articleId//10      #每10楼1页
    browser.get(dlCompainMainPage)
    time.sleep(1)
    for i in range(1,pagecnt):
        browser.execute_script("window.scrollTo(0,document.body.scrollHeight)")
        time.sleep(2)
    articles = browser.find_elements_by_xpath('//article')
    if(articleId>=len(articles)):
        browser.execute_script("window.scrollTo(0,document.body.scrollHeight)")
        time.sleep(2)
        browser.execute_script("window.scrollTo(0,document.body.scrollHeight)")
        time.sleep(2)
    articles = browser.find_elements_by_xpath('//article')
    return(articles)
    
def GetComplainLinks():
    time.sleep(3.5)
    link = browser.find_elements_by_xpath('//a[span[contains(text(),"网页链接")]]')
    l=[]
    for i in range(0, len(link)):
        l.append(link[i].get_attribute("href"))
    return(l)

def DoComplain(i, link):   
    browser.get(link)
    browser.implicitly_wait(2)
    harmfulInfo = browser.find_element_by_link_text(complainType[i]).click()
    browser.execute_script('window.scrollBy(0,400)')
    others= browser.find_element_by_link_text(compSubType[i]).click()
    if i == 3:
        time.sleep(0.5)
        browser.find_element_by_css_selector('textarea').clear()
        browser.find_element_by_css_selector('textarea').send_keys(attackReason)
        # browser.find_element_by_xpath("//input[@action-type='blackUser']").click()
        time.sleep(0.25)
    checkBox = browser.find_element_by_xpath("//input[@name='chk']").click()
    time.sleep(0.25)
    comment_button = browser.find_element_by_link_text(u"提交").click()
    time.sleep(0.75)

def DLComplain_All(typeIds,startId,endId):
    global running
    start=1 #考虑置顶页
    if dlCompainMainPage == dlCompainMainPages[2]:
        start=0
    end = 999999
    if startId.get() and startId.get().isdigit() and int(startId.get())>start:  #是否空值且为数字
        start=int(startId.get())-1
        if endId.get() and endId.get().isdigit():  #是否空值且为数字
            end=int(endId.get())

    articleId = start        #开始的楼
    articles=[]
    while articleId < end and running == 1:
        articles = GetArticles(articleId)
        if(articleId>=len(articles)):
            break
        articles[articleId].click()
        time.sleep(0.25)
        articleId = articleId+1
        try:
            links=GetComplainLinks()
        except:
            continue
        for link in links:
            if running == 1:
                try:
                    for i in range(len(typeIds)):
                        if typeIds[i].get() == 1 and running == 1:
                            DoComplain(i, link)
                            root.update()
                            time.sleep(0.1)
                        elif running == 0:    
                            break
                except:
                    continue    
            else:
                break 
    if articleId == end or running == 0:
        browser.get(dlCompainMainPage)
        showinfo(title=u'完成', message=u"本轮完成楼数:" + str(start+1) +u"—"+ str(articleId-1+1) +u"，共"+ str(articleId-start)+u"楼。")

def DLComplain_Single(typeIds,startId,endId):
    global running
    back_url = browser.current_url  
    browser.execute_script('var q=document.documentElement.scrollTop=0')
    try:
        browser.find_element_by_xpath('//*[contains(text(),"DL民间反黑组")]')
    except:
        try:
            browser.find_element_by_xpath('//*[contains(text(),"寺拉利")]')
        except:
            return    
    try:
        browser.find_element_by_xpath('//*[contains(text(),"发表评论")]')
        links=GetComplainLinks()
        start=0
        end=len(links)
        if startId.get() and startId.get().isdigit() and int(startId.get())>start:  #是否空值且为数字
            start=int(startId.get())-1
            if endId.get() and endId.get().isdigit():  #是否空值且为数字
                end=int(endId.get())
        for linkId in range(start, end):
            if running == 1:
                try:
                    for i in range(len(typeIds)):
                        if typeIds[i].get() == 1 and running == 1:
                            DoComplain(i, links[linkId])
                            root.update()
                            time.sleep(0.1)
                        elif running == 0:    
                            break
                            break
                except:
                    continue
            else:
                break
    except:
        showerror(title=u'错误', message=u'请确认DL反黑楼已正确打开')
    browser.get(back_url)

###########################       UI         ############################

def UIStartClicked(autoMode, stationId, typeIds,startId,endId):
    global running
    running = 1
    global dlCompainMainPage
    dlCompainMainPage = dlCompainMainPages[stationId.get()]
    if autoMode.get()==1:
        DLComplain_All(typeIds,startId,endId)
    elif autoMode.get()==2:
        DLComplain_Single(typeIds,startId,endId)

def UIStopClicked():
    global running
    running = 0

def ShowMenu():
    sw = root.winfo_screenwidth()
    sh = root.winfo_screenheight()
    root.geometry("+%d+%d"%(sw/2+340,sh/2-240))

    typeIds = []
    startId = StringVar()
    endId = StringVar()
    autoMode = IntVar()
    stationId = IntVar()

    root.title(u"DL反黑")
    try:
        img = Image("photo", file="icon.gif")
        root.call('wm', 'iconphoto', root._w, img)
    except:
        Label(root,text=u"Tips:在程序位置放icon.gif可设置为图标").grid(row=5,rowspan=1,column=0,columnspan=20, sticky=EW)
    
    for i,text in zip(range(len(selectMenu)),selectMenu):
        typeIds.append(IntVar())
        CB = Checkbutton(root, text=text, variable=typeIds[-1])
        CB.select()
        CB.grid(row=0,column=4*i,columnspan=4,sticky=EW)
    typeIds[4].set(0)

    Radiobutton(root,text=u'全自动',variable=autoMode,value=1).grid(row=1,rowspan=1,column=0,columnspan=3,sticky=W)
    Radiobutton(root,text=u'半自动',variable=autoMode,value=2).grid(row=2,rowspan=1,column=0,columnspan=3,sticky=W)
    
    Radiobutton(root,text=u'反黑组',variable=stationId,value=1).grid(row=1,rowspan=1,column=4,columnspan=3,sticky=W)
    Radiobutton(root,text=u'二号机',variable=stationId,value=2).grid(row=2,rowspan=1,column=4,columnspan=3,sticky=W)

    Label(root,text=u"从").grid(row=1,rowspan=1,column=10,columnspan=1,sticky=W)
    Entry(root,width=3,textvariable=startId).grid(row=1,rowspan=1,column=11,columnspan=1,sticky=W)
    Label(root,text=u"到").grid(row=1,rowspan=1,column=12,columnspan=1,sticky=W)
    Entry(root,width=3,textvariable=endId).grid(row=1,rowspan=1,column=13,columnspan=1,sticky=W)
    Label(root,text=u"(选填)").grid(row=1,rowspan=1,column=14,columnspan=2,sticky=W)

    Label(root,text=u"楼数(全自动) 或 链接序号(半自动)").grid(row=2,rowspan=1,column=10,columnspan=10,sticky=W)
    autoMode.set(1)
    stationId.set(1)

    Button(root,text=u'开始',command=lambda:UIStartClicked(autoMode, stationId, typeIds,startId,endId)).grid(row=3,rowspan=2,column=0, columnspan=11, sticky=EW)
    Button(root,text=u'停止',command=UIStopClicked).grid(row=3,rowspan=2,column=11,columnspan=10, sticky=EW)

    root.mainloop()

def browserquit():
    try:
        browser.quit()
    except:
        None
    try:
        os.system('taskkill /im chromedriver.exe /F')
    except:
        None
    try:
        root.destroy()
    except:
        None
    os._exit(0)

if __name__ == '__main__':
    try:
        Weibo_login()
    except:
        print("-")
    finally:
        browserquit()

